library login;

import 'dart:async';
import 'dart:math' as math;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import '../../utils/tools.dart';
import '../../utils/api.dart';
import '../../application.dart';
import 'captcha_dialog.dart';

part 'login.dart';
part 'register.dart';
part 'forgot.dart';

void toast(String message, [int time = 2, String align = 'top']) {
  app.toast(message, time, align);
}

class StateButton extends StatelessWidget {
  final bool isLoading;
  final void Function()? onPressed;
  final String text;
  final Color textColor;
  final ButtonStyle? style;
  final EdgeInsetsGeometry padding;

  const StateButton({
    Key? key,
    this.isLoading = false,
    this.onPressed,
    this.text = '提交',
    this.style,
    this.padding = const EdgeInsets.symmetric(vertical: 5, horizontal: 20),
    this.textColor = Colors.white,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      style: style ??
          ButtonStyle(
            foregroundColor: MaterialStateProperty.all(textColor),
            side: MaterialStateProperty.all(
              const BorderSide(color: Colors.white),
            ),
          ),
      child: Padding(
        padding: padding,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            if (isLoading)
              Padding(
                padding: const EdgeInsets.only(right: 8),
                child: SizedBox(
                  width: 14,
                  height: 14,
                  child: CircularProgressIndicator(
                    color: textColor,
                    strokeWidth: 2,
                  ),
                ),
              ),
            Text(text),
          ],
        ),
      ),
    );
  }
}

class LoginTheme {
  static InputBorder inputBorder = const UnderlineInputBorder(
    borderSide: BorderSide(color: Colors.white54, width: 0.5),
    borderRadius: BorderRadius.all(Radius.circular(0)),
  );

  static TextStyle linkStyle =
      const TextStyle(color: Colors.white, fontSize: 13);

  static InputDecoration inputDecoration(String label,
      {IconData icon = Icons.arrow_forward, Widget? action}) {
    return InputDecoration(
      border: inputBorder,
      enabledBorder: inputBorder,
      labelText: label,
      labelStyle: const TextStyle(color: Colors.white54),
      //hintText: label,
      //hintStyle: TextStyle(color: Colors.white54),
      counterText: '',
      prefixIcon: Icon(icon, color: Colors.white54),
      suffixIcon: action,
      contentPadding: const EdgeInsets.all(0),
    );
  }
}

class IndexPage extends StatefulWidget {
  final Map<String, dynamic>? arguments;

  const IndexPage({Key? key, this.arguments}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with SingleTickerProviderStateMixin {
  String _title = "会员登录";
  String? currentPanel = 'login';

  double windowWidth = 0;
  late AnimationController animationController;
  late Matrix4 transform;
  late Animation<double> _tween;
  late Widget currentWidget;

  int curDirection = 1;

  static _IndexPageState of(BuildContext context) {
    return context.findAncestorStateOfType<_IndexPageState>()!;
  }

  @override
  initState() {
    super.initState();
    animationController = AnimationController.unbounded(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );
    animationController.value = 0;
    animationController.addListener(_onRotate);
    transform = Matrix4.identity()
      ..setEntry(3, 2, 0.0)
      ..rotateY(0);
    currentPanel = widget.arguments?['panel'];
    switch (currentPanel) {
      case 'register':
        _title = '会员注册';
        currentWidget = const RegisterPanel();
        break;
      case 'forgot':
        _title = '找回密码';
        currentWidget = const ForgotPanel();
        break;
      default:
        _title = '会员登录';
        currentWidget = const LoginPanel();
        return;
    }
  }

  setTitle(String title) {
    setState(() {
      _title = title;
    });
  }

  changePanel(String panel, {direction = 'rl'}) {
    if (panel == currentPanel) return;
    Widget newWidget;
    switch (panel) {
      case 'login':
        setTitle('会员登录');
        newWidget = const LoginPanel();
        break;
      case 'register':
        setTitle('会员注册');
        newWidget = const RegisterPanel();
        break;
      case 'forgot':
        setTitle('找回密码');
        newWidget = const ForgotPanel();
        break;
      default:
        return;
    }
    if (direction == 'rl') {
      curDirection = 1;
    } else {
      curDirection = -1;
    }
    doChangePanel(newWidget);
  }

  doChangePanel(Widget panel) {
    _tween =
        animationController.drive<double>(CurveTween(curve: Curves.easeInBack));
    animationController.animateTo(1).whenComplete(() {
      currentWidget = panel;
      animationController.value = 1;
      curDirection = -curDirection;
      animationController.animateTo(0);
    });
  }

  _onRotate() {
    var arcValue = _tween.value * math.pi * curDirection / 2;
    var entry = getEntry(arcValue);
    //app.log.d([_tween.value,arcValue,entry]);
    setState(() {
      transform = Matrix4.identity()
        ..setEntry(3, 2, entry)
        ..rotateY(arcValue);
    });
  }

  getEntry(double angle) {
    return (math.sin(angle) / windowWidth).abs();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    windowWidth = size.width;

    return Scaffold(
      extendBodyBehindAppBar: true,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          _title,
          style: const TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.black12,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      //resizeToAvoidBottomPadding: true,
      body: Container(
        decoration: const BoxDecoration(
          color: Colors.blue,
          image: DecorationImage(
            image: AssetImage('assets/images/login-bg.jpg'),
            fit: BoxFit.cover,
          ),
        ),
        alignment: const Alignment(0, -0.6),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 15.0, sigmaY: 15.0),
          child: SafeArea(
            child: Transform(
              transform: transform,
              alignment: Alignment.center,
              child: FittedBox(
                alignment: Alignment.topCenter,
                child: Container(
                  width: math.min(400, windowWidth - 60),
                  padding: const EdgeInsets.all(20),
                  decoration: const BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  ),
                  child: currentWidget,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
